<template>
  <div style="padding:0 15px;">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">

      <el-form-item label="字段名称" prop="fieldName">
        <el-input
          v-model="queryParams.fieldName"
          placeholder="请输入字段名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="字段类型" prop="fieldType">
        <el-select v-model="queryParams.fieldType" placeholder="请选择字段类型" clearable>
          <el-option
            v-for="dict in dict.type.hd_form_field_type"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
<!--      <el-form-item label="提示文字" prop="fieldTips">-->
<!--        <el-input-->
<!--          v-model="queryParams.fieldTips"-->
<!--          placeholder="请输入提示文字"-->
<!--          clearable-->
<!--          @keyup.enter.native="handleQuery"-->
<!--        />-->
<!--      </el-form-item>-->
      <el-form-item label="是否必填" prop="reqFill">

      <el-select v-model="queryParams.reqFill" placeholder="是否必填" clearable>
        <el-option
          v-for="dict in dict.type.hd_common_req"
          :key="dict.value"
          :label="dict.label"
          :value="dict.value"
        />
      </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['apply:formField:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['apply:formField:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['apply:formField:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['apply:formField:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="fieldList" @selection-change="handleSelectionChange">
<!--      <el-table-column type="selection" width="55" align="center" />-->
<!--      <el-table-column label="表单字段ID" align="center" prop="formFieldId" />-->
<!--      <el-table-column label="表单ID" align="center" prop="formId" />-->
      <el-table-column label="字段名称" align="center" prop="fieldName" />
      <el-table-column label="字段类型" align="center" prop="fieldType">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.hd_form_field_type" :value="scope.row.fieldType"/>
        </template>
      </el-table-column>
      <el-table-column label="提示文字" align="center" prop="fieldTips" />
      <el-table-column label="是否必填" align="center" prop="reqFill">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.hd_common_req" :value="scope.row.reqFill"/>
        </template>
      </el-table-column>
<!--      <el-table-column label="初始数据" align="center" prop="initialData" />-->
<!--      <el-table-column label="限制信息" align="center" prop="restrictJson" />-->
      <el-table-column label="排序" align="center" prop="fieldSort" />
<!--      <el-table-column label="备注" align="center" prop="remark" />-->
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['apply:formField:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['apply:formField:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改表单字段对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="50%" append-to-body center>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
<!--        <el-form-item label="表单ID" prop="formId">
          <el-input v-model="form.formId" placeholder="请输入表单ID" />
        </el-form-item>-->
        <div style="display: flex;justify-content: space-between">
          <el-form-item label="字段名称" prop="fieldName" style="width:48%">
            <el-input v-model="form.fieldName" placeholder="请输入字段名称" />
          </el-form-item>
          <el-form-item label="英文名称" prop="fieldEnName" style="width:48%">
            <el-input v-model="form.fieldEnName" placeholder="请输入字段名称" @change="isHasEnfieldName" :disabled="isEnfieldNameDisable"/>
          </el-form-item>
        </div>

        <el-form-item label="字段类型" prop="fieldType" >
          <el-select v-model="form.fieldType" placeholder="请选择字段类型" @change="handleChange">
            <el-option
              v-for="dict in dict.type.hd_form_field_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="提示文字" prop="fieldTips">
          <el-input v-model="form.fieldTips" placeholder="请输入提示文字" />
        </el-form-item>

        <el-form-item label="是否必填" prop="reqFill">
          <el-radio-group v-model="form.reqFill" @input="isflagMast">
            <el-radio
              v-for="dict in dict.type.hd_common_req"
              :key="dict.value"
              :label="dict.value"
            >{{dict.label}}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="初始数据" ref="dataArrCopy">
          <div>
            <!--附键-->
            <div v-if="fjtype&&!kjfjtype" style="margin-bottom:10px;">
              <el-select v-model="dataArrCopy.dataArr[0].data" placeholder="请选择上传附键类型" @change="fjtypeChange">
                <el-option
                  v-for="item in fjOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>
            </div>
            <!--可见附键-->
            <div v-if="kjfjtype&&!fjtype" style="margin-bottom:10px;">
              <el-select v-model="dataArrCopy.dataArr[0].data" placeholder="请选择上传可见附键类型" @change="kjfjtypeChange">
                <el-option
                  v-for="item in kjfjOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>
            </div>
            <!--单选多选或其他表单-->
            <div class="cssjInput" v-for="(item,index) in dataArrCopy.dataArr" :key="item.id" v-if="!kjfjtype&&!fjtype">
              <el-input v-model="item.data" placeholder="请输入初始数据数据" style="width: 82%" @input="inputChange(item.id,item.data)"/>
              <el-button  size="mini" @click="deleteInput(item)">删除</el-button>
            </div>
            <el-button  size="mini" @click="addInput">新增</el-button>
          </div>
        </el-form-item>

        <!--限制信息-->
        <template v-if="formatterObj!=null">
        <div v-if="form.fieldType=='Input'||form.fieldType=='textarea'">

          <el-form-item label="字符长度" >
            <el-input type="number" v-model="formatterObj.formatter.len" placeholder="请输入字符长度"   @input="sizeInputChange"/>
          </el-form-item>
        </div>
        </template>
        <div v-if="form.fieldType=='upload'||form.fieldType=='upload_view'">
          <el-form-item label="文件大小" >
            <el-input type="number" v-model="''||formatterObj.formatter.size" placeholder="请输入文件大小"   @input="wjSizeInputChange"/>
          </el-form-item>
        </div>


        <el-form-item label="排序" prop="fieldSort">
          <el-input-number v-model="form.fieldSort"  :min="0"  ></el-input-number>
        </el-form-item>
<!--        <el-form-item label="备注" prop="remark">-->
<!--          <el-input v-model="form.remark" placeholder="请输入备注" />-->
<!--        </el-form-item>-->
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm" round>确 定</el-button>
        <el-button @click="cancel" round>取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listField, getField, delField, addField, updateField, isHasEn } from "@/api/match/field";

export default {
  props:{
    bdInfo:{
      type:Object,
      default:null
    },
    isDrawer:{
      type:Boolean,
      default: false
    }
  },
  name: "Field",
  dicts: ['hd_form_field_type','hd_common_req'],
  data() {
    return {
      //英文字段是否可以修改
      isEnfieldNameDisable:false,
      //限制信息格式
      formatterObj:{
        type:'',
        formatter:{},
      },
      //初始数据格式
      dataArrCopy:{},
      //可见附键类型
      kjfjOptions: [
        {value: 'img', label: '图片'},
        {value: 'video', label: '视频'},
        {value: 'audio', label: '音频'},
        ],
      kjfjtype:false,
      //附键类型
      fjOptions: [
        {value: 'word', label: 'Word'},
        {value: 'pdf', label: 'PDF'},
        {value: 'ppt', label: 'PPT'},
        {value: 'excel', label: 'Excel'},
      ],
      fjtype:false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 表单字段表格数据
      fieldList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        formId: null,
        fieldName: null,
        fieldType: null,
        fieldTips: null,
        reqFill: null,
      },
      //当是radio和checkBox时，要增加input初始id值
      dataNum:0,
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        fieldName: [
          { required: true, message: '请输入字段名称', trigger: 'blur' },
        ],
        fieldEnName: [
          { required: true, message: '请输入字段英文名称', trigger: 'blur' },
        ],
        fieldType:[
          { required: true, message: '请选择字段类型', trigger: 'blur' },
        ],

      }
    };
  },




  created() {
    this.getList();
  },

  watch:{

    bdInfo: {
      handler(newVal,oldVal) {

          this.loading = true;
          this.queryParams.formId=this.bdInfo.formId
          listField(this.queryParams).then(response => {
            this.fieldList = response.rows;
            this.total = response.total;
            this.loading = false;
            console.log('表ge显示',this.fieldList)

          });


      },
      deep: true,
      immediate: true
    }

  },

  methods: {
    /**创建字段**/
    /**
     * Radio
     VM93659 index.vue:267 Checkbox
     VM93659 index.vue:267 DatePicker
     VM93659 index.vue:267 TimePicker
     VM93659 index.vue:267 DateTimePicker
     VM93659 index.vue:267 Input
     VM93659 index.vue:267 textarea
     upload 附键选择  pdf world excel
     upload_view 可预览附键   图片，音频，视频
     **/

    //给原来的空对象设置属性确保html能够访问到
    resetDataArrCopy() {
      this.dataArrCopy={
        type:'',
        dataArr:[]
      }
    },



    /**初始化初始数据表单*/
    initClearData(){
      //附键是否显示
      this.kjfjtype=false; //隐藏可见附键
      this.fjtype=false;   //隐藏附键
      //初始数据
      this.resetDataArrCopy()
    },

    /**选择类型*/
    handleChange(val){
      this.initClearData()//初始化初始数据
      this.dataArrCopy.type=val;  //保存数据类型 type:''

      //限制信息

    },
/************添加初始数据dataArr[id:'',data:'']******************/
    /**填写初始数据*/
    inputChange(index,val){
      console.log(index,val)
      this.dataArrCopy.dataArr[index].data=val  //并保存到容器中
    },

    /**选择可见附键类型*/
    kjfjtypeChange(val){
      this.dataArrCopy.dataArr[0].data=val   //可见附键保存到容器中
    },

    /**选择附键类型*/
    fjtypeChange(val){
      this.dataArrCopy.dataArr[0].data=val   //附键保存到容器中
    },

    /**选择类型后增加表单【点击增加表单按钮】*/
    addInput(){
      console.log('aaaa',this.form)
      //未选择字段类型停止向下进行，并提示
      if(this.form.fieldType==null) return this.$modal.msgWarning("请先选择字段类型")
      //可见附键和附件类型
      if(this.form.fieldType=='upload_view'){
        this.kjfjtype=true;//显示可见附键选择器
        if(this.dataArrCopy.dataArr.length!=0)  return this.$modal.msgWarning("该字段类型只能添加一条数据")
        this.dataArrCopy.dataArr.push({
          id:0,
        })//保存id到容器
      }
      //附键
      if(this.form.fieldType=='upload'){
        this.fjtype=true;//显示附键选择器
        if(this.dataArrCopy.dataArr.length!=0)  return this.$modal.msgWarning("该字段类型只能添加一条数据")
        this.dataArrCopy.dataArr.push({
          id:0,
        })//保存id到容器
      }
      //添加表单
      if(!this.kjfjtype&&!this.fjtype){//查看附键选择器是否隐藏
        //多选表单【可以建立多个表单】
        if(this.form.fieldType=='Radio'||this.form.fieldType=='Checkbox'){
          this.dataArrCopy.dataArr.push({
            id:this.dataNum++,   //点击一次表单id增加1  并将id存到容器中并建立1个表单
          })
        }else{
          //添加单个表单
          //如果表单容器中已经有数据说明已经有表单，再点击不会增加表单，始终只有一个
          if(this.dataArrCopy.dataArr&&this.dataArrCopy.dataArr.length!=0)  return this.$modal.msgWarning("该字段类型只能添加一条数据")
          this.dataArrCopy.dataArr.push({
            id:0,
          })
        }
      }
    },
/***************--***************/

    /**判断英文字段是否已经存在*/
    isHasEnfieldName(){
        isHasEn({formId:this.bdInfo.formId,fieldEnName:this.form.fieldEnName}).then(res=>{
          if(!res.data) return this.$modal.msgError("英文字段不能重复")
        })
    },
    /**删除表单*/
    deleteInput(item){
      var index = this.dataArrCopy.dataArr.indexOf(item)
      if (index !== -1) {
        this.dataArrCopy.dataArr.splice(index, 1)
      }
    },

    /**
     限制信息
     */
    //输入长度
    sizeInputChange(e){
      if(this.form.fieldEnName=='') return this.$modal.msgWarning("请先填写英文字段名称")
      this.formatterObj.type=this.form.fieldEnName
      this.formatterObj.formatter.len=e

    },

    wjSizeInputChange(e){
      if(this.form.fieldEnName=='') return this.$modal.msgWarning("请先填写英文字段名称")
      this.formatterObj.type=this.form.fieldEnName
      this.formatterObj.formatter.size=e
    },
    //是否必填
    isflagMast(val){
      this.formatterObj.formatter.isRequired=val
    },


    /** 查询表单字段列表 */
    getList() {
      this.loading = true;
      this.queryParams.formId=this.bdInfo.formId
      listField(this.queryParams).then(response => {
        this.fieldList = response.rows;
        this.total = response.total;
        this.loading = false;
        console.log('表ge显示',this.fieldList)

      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },

    // 表单重置
    reset() {
      this.form = {
        formFieldId: null,
        formId: null,
        fieldName: null,
        fieldEnName:null,
        fieldType: null,
        fieldTips: null,
        reqFill: '0',
        initialData: null,
        restrictJson: null,
        fieldSort: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.formFieldId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },


    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.form.formId=this.bdInfo.formId
      this.open = true;
      this.title = "添加表单字段";
      this.initClearData()//初始化初始数据
      this.dataNum=0;
      this.formatterObj={type:'',formatter:{}}
      this.isEnfieldNameDisable=false;
      this.formatterObj.formatter.isRequired=this.form.reqFill

    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.isEnfieldNameDisable=true;
      this.reset();
      const formFieldId = row.formFieldId || this.ids
      getField(formFieldId).then(response => {
        console.log(response)
        //回显初始数据到form弹框
        //初始数据
        this.initClearData()//初始化初始数据
        if(response.data.initialData!=null) {
          this.dataArrCopy = {...JSON.parse(response.data.initialData)}
        }else{
          this.resetDataArrCopy()
        }
        //console.log(this.dataArrCopy)
        if(this.dataArrCopy.type=='upload_view'){
          this.kjfjtype=true;
        }else{
          this.kjfjtype=false;
        }
        if(this.dataArrCopy.type=='upload'){
          this.fjtype=true;
        }else{
          this.fjtype=false;
        }
        //限制信息
        if(response.data.restrictJson!=null){
          this.formatterObj={...JSON.parse(response.data.restrictJson)}
          this.formatterObj.formatter.isRequired=response.data.reqFill
          this.formatterObj.type=response.data.fieldEnName
        }else{
          this.formatterObj={
            type:'',
            formatter:{},
          }

        }


        this.form = response.data;
        this.open = true;
        this.title = "修改表单字段";
      });
    },
    /** 提交按钮 */
    submitForm() {


      this.$refs["form"].validate(valid => {
        if (valid) {
          if(this.dataArrCopy.dataArr&&this.dataArrCopy.dataArr.length==0) return this.$modal.msgWarning("请填写或选择初始数据")
          if(this.formatterObj.formatter=={}) return this.$modal.msgWarning("请填写限制条件")
          this.form.initialData=JSON.stringify(this.dataArrCopy)
          this.form.restrictJson=JSON.stringify(this.formatterObj)
          if (this.form.formFieldId != null) {
            updateField(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            isHasEn({formId:this.bdInfo.formId,fieldEnName:this.form.fieldEnName}).then(res=>{
              if(!res.data) return this.$modal.msgError("英文字段不能重复")
              this.formatterObj.type=this.form.fieldEnName
              this.form.restrictJson=JSON.stringify(this.formatterObj)
             // console.log(this.form.fieldEnName)
            console.log(this.form)
            addField(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
            });
          }
        }

      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const formFieldIds = row.formFieldId || this.ids;
      this.$modal.confirm('是否确认删除表单字段编号为"' + formFieldIds + '"的数据项？').then(function() {
        return delField(formFieldIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('apply/formField/export', {
        ...this.queryParams
      }, `formField_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
<style scoped lang="scss">
::v-deep{
  .el-checkbox__label{display: none}
  .el-dialog {
    border-radius: 11px;
  }
  .el-dialog {
    border-radius: 11px;
  }
}

.cssjInput{display: flex;justify-content: space-between;margin-bottom: 10px;}
</style>
